package com.example.dajian_hou.service.impl;

import com.example.dajian_hou.entity.User;
import com.example.dajian_hou.mapper.UserMapper;
import com.example.dajian_hou.service.UserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(String username, String password) {
        return userMapper.findByUsernameAndPassword(username, password);
    }

    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }

    @Override
    public User findById(Long id) {
        return userMapper.findById(id);
    }

    @Override
    public Map<String, Object> findByPage(Integer pageNum, Integer pageSize, String keyword) {
        PageHelper.startPage(pageNum, pageSize);

        // 构建查询条件
        User condition = new User();
        if (StringUtils.hasText(keyword)) {
            condition.setUsername(keyword);
            condition.setNickname(keyword);
            condition.setPhone(keyword);
        }

        Page<User> page = (Page<User>) userMapper.findByCondition(condition);

        Map<String, Object> result = new HashMap<>();
        result.put("records", page.getResult());
        result.put("total", page.getTotal());

        return result;
    }

    @Override
    public void save(User user) {
        userMapper.insert(user);
    }

    @Override
    public void update(User user) {
        userMapper.update(user);
    }

    @Override
    public void deleteById(Long id) {
        userMapper.deleteById(id);
    }

    @Override
    @Transactional
    public void deleteByIds(List<Long> ids) {
        for (Long id : ids) {
            userMapper.deleteById(id);
        }
    }

    @Override
    public boolean verifyPassword(Long userId, String password) {
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        // 这里应该使用加密后的密码进行比较
        return user.getPassword().equals(password);
    }

    @Override
    public void updatePassword(Long userId, String newPassword) {
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        // 更新密码
        user.setPassword(newPassword);
        userMapper.update(user);
    }

    @Override
    public void updateUserInfo(User user) {
        userMapper.update(user);
    }
}
